package cn.itcast.dao;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import cn.itcast.utils.JDBCUtils;
import cn.itcast.vo.User;

public class UserDaoImple implements UserDao {


	//注册
	public void register(User user) {
		//创建QueryRunner对象
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		//编写SQL
		String sql = "insert into user(username,password,type) values(?,?,'user') ";
		try {
			int i = queryRunner.update(sql, user.getUsername(),user.getPassword());
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("用户注册失败!");
		}
	}

//登录
	public User login(User user) {
		//创建QueryRunner对象
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		//编写SQL
		String sql = "select * from user where username = ? and password = ?";
		User existUser;
		try {
			existUser = queryRunner.query(sql, new BeanHandler<User>(User.class), user.getUsername(),user.getPassword());
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("用户登录失败!");
		}
		return existUser;
	}

	public int ajax(String username) throws SQLException {
		QueryRunner queryRunner=new QueryRunner(JDBCUtils.getDataSource());
		String sql="select * from user where username =?";
		User user=queryRunner.query(sql,new BeanHandler<User>(User.class), username);
		if (user==null){
			return 1;
		}else {
			return 0;
		}
	}


}
